package com.gjt.stream;



import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;


/**
 * Created with Intel IDEA.
 * 阅读器（java.io.Reader）:指定读取字符的api
 *  重要的具体子类InputStreamReader,包含了一个底层输入流，可以从中读取原始字节
 *  原始阅读器FileReader,
 *          StringReader,CharArrayReader:java内部使用
 *  过滤器阅读器(java.io.FilterReader):
 *          BufferedReader(基于字符的，内部使用字符数组做缓冲，读取时首先从缓存拿，没有的话从底层流读取),LineNumberReader,PushbackReader
 *
 * @Auther: gjt
 * @Date: 2024/3/19 21:23
 */
public class Read {

    // 使用FileReader 读取字符
    public static char[] read()  {
        char[] chars = new char[1024];
        try(FileReader fileReader = new FileReader("C:/Users/23152/Desktop/hello.txt")){
                int count = fileReader.read(chars);
                System.out.println("读取"+count+"字符");
        }catch (IOException e){
            e.printStackTrace();
        }
        return chars;
    }

    // 使用InputStreamReader 读取字符
    private static String read1() {
        StringBuilder stringBuilder = new StringBuilder();
        try(InputStream in = Files.newInputStream(Paths.get("C:/Users/23152/Desktop/hello.txt"))){
            InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
            int c;
            while((c=reader.read()) != -1){
                stringBuilder.append((char)c);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    // 使用BufferedReader 读取（不过也是一次读取一个字符）
    private static String read2() {
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader=new InputStreamReader(Files.newInputStream(Paths.get("C:/Users/23152/Desktop/hello.txt")))){
            BufferedReader bufReader = new BufferedReader(reader, 1024);
            int c;
            while((c = bufReader.read()) != -1){
                stringBuilder.append((char) c);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    // BufferedReader的readLine 读取一行
    private static String read3() {
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader=new InputStreamReader(Files.newInputStream(Paths.get("C:/Users/23152/Desktop/hello.txt")))){
            BufferedReader bufReader = new BufferedReader(reader, 1024);
            String s;
            while(!Objects.isNull(s = bufReader.readLine())){
                stringBuilder.append(s);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }


    public static void main(String[] args) throws IOException {
//        String s = read1();
        String s = read3();
        System.out.println(s);
    }
}
